package com.example.myimageshare.View;


import android.content.Context;
import android.graphics.Color;
import android.icu.util.LocaleData;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.myimageshare.R;
import com.example.myimageshare.Utils.LoginUtil;
import com.example.myimageshare.adapter.DeleteAdapter;
import com.example.myimageshare.adapter.HomeAdapter;
import com.example.myimageshare.adapter.ImageListAdapter;
import com.example.myimageshare.domain.User;
import com.example.myimageshare.domain.UserArt;
import com.example.myimageshare.entity.PhotoItem;
import com.example.myimageshare.entity.UserArtItem;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobBatch;
import cn.bmob.v3.BmobObject;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BatchResult;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.datatype.BmobQueryResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.DeleteBatchListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListListener;
import cn.bmob.v3.listener.SQLQueryListener;


/**
 * A simple {@link Fragment} subclass.
 */
public class DeleteFragment extends Fragment {

    public static final String TAG = DeleteFragment.class.getSimpleName();

    //
    FloatingActionButton fab;
    FloatingActionButton fab_confirm;

    //适配器
    private DeleteAdapter adapter = null;

    //
    private OnFragmentInteractionListener mListener;

    //选中的图片URL
    private List<String> imgUrlSelected = new ArrayList<String>();
    private List<String> objectIds = new ArrayList<>();
    //RecyclerView对象
    private RecyclerView recyclerView = null;
    //SwipeRefreshLayout对象
    private SwipeRefreshLayout swipe = null;
    //    数据对象
    List<UserArt> users = new ArrayList<>();

    //  上下文
    Context context;
    View rootView;
    LinearLayoutManager llm;
    GridLayoutManager glm;
    ImageView imageView = null;

    private static boolean tf = false;

    public DeleteFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savadInstanceState){
        super.onCreate(savadInstanceState);
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        context = getActivity();
        final View rootView = inflater.inflate(R.layout.fragment_delete,
                container,false);
        fab = rootView.findViewById(R.id.fab_delete);
        fab_confirm = rootView.findViewById(R.id.fab_delete_confirm);
        fab_confirm.setVisibility(View.GONE);
        fab_confirm.setEnabled(false);
        recyclerView = rootView.findViewById(R.id.lv_img_delete_list);
        swipe = rootView.findViewById(R.id.swipe_delete);

//        llm = new LinearLayoutManager(context);
//        recyclerView.setLayoutManager(llm);
        glm = new GridLayoutManager(context,2);
        recyclerView.setLayoutManager(glm);
        swipe.setRefreshing(true);
        initData();

        swipe.setEnabled(true);
        /*下拉触发事件*/
        swipe.setOnRefreshListener(
                new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        initData2();
                    }
                }
        );

        /*点击将图片可选状态*/
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tf = !tf;
                adapter.setIsDelete(tf);
                adapter.notifyDataSetChanged();
                Log.d(TAG, "显示删除按钮" + tf);
                if (mListener != null) {
                    onImageDelete(tf);

                }
                if(tf) {
                    fab_confirm.setVisibility(View.VISIBLE);
                }else{
                    fab_confirm.setVisibility(View.GONE);
                }
                fab_confirm.setEnabled(tf);
            }
        });
        //确认删除
        fab_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mListener != null) {
                    onDeleteConfirm(deleteResults());
                }
            }
        });



        return rootView;
    }

    /*适配器回调
    * */
    public void changeSelect(){
        // (0/9)完成动态变化
        adapter.setOnItemSelectChanged(new DeleteAdapter.OnItemSelectChanged() {
            @Override
            public void changeSelectedCount(List<UserArt> selectedImages) {
                UserArtItem item = new UserArtItem();
                if (selectedImages.size() == 0) {
                    item.setEnable(false);
                    item.setText("选中");
                    if (mListener != null) {
                        onSelectedItem(item);
                        Log.d(TAG, "null选中" + selectedImages.size());
                    }
                    return;
                }
                item.setEnable(true);
                item.setTextColor(Color.WHITE);
                item.setText("("+selectedImages.size()+"/9)选中");
                if (mListener != null) {
                    onSelectedItem(item);
                    if(selectedImages.size()!=0) {
                        setDeleteArray(selectedImages);
                    }
                }
            }
        });
    }

    /*回调接口*/
    public interface OnFragmentInteractionListener {

        void onFragmentInteraction(String s);

        void onFragmentInteraction(UserArtItem item);

        void  OnFabConfirm(int imgs);

    }

    /*添加每一个Url到一个List<String>*/
    private void setDeleteArray(List<UserArt> userArts ){
        //初始化
        imgUrlSelected.clear();
        objectIds.clear();
        //遍历至UserArt中的urls
        for (UserArt u : userArts) {
            objectIds.add(u.getObjectId());
            for (String url:u.getUrls()) {
                imgUrlSelected.add(url);
            }
        }
    }
    /*批量删除选中结果*/
    public int deleteResults(){
        //删除文件系统的图
        //List<String>转String[]
        final String[] urls = imgUrlSelected.toArray(new String[imgUrlSelected.size()]);
        final int[] delete_success = {urls.length};
        BmobFile.deleteBatch(urls, new DeleteBatchListener() {;
            @Override
            public void done(String[] failUrls, BmobException e) {
                if(e==null){
                    delete_success[0] = urls.length;

                }else{
                    if(failUrls!=null){
                        delete_success[0] = urls.length - failUrls.length;
                        Toast.makeText(context,"删除失败个数："
                                        +failUrls.length+","+e.toString(),
                                Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(context,"全部删除失败！",Toast.LENGTH_SHORT);
                    }
                }
            }
        });

        //删除UserArt表信息
        List<BmobObject> userArtList = new ArrayList<>();
        for (String u:objectIds) {
            UserArt uu = new UserArt();
            uu.setObjectId(u);
            userArtList.add(uu);
        }
        new BmobBatch().deleteBatch(userArtList).doBatch(new QueryListListener<BatchResult>() {

            @Override
            public void done(List<BatchResult> results, BmobException e) {
                if (e == null) {
                    for (int i = 0; i < results.size(); i++) {
                        BatchResult result = results.get(i);
                        BmobException ex = result.getError();
                        if (ex == null) {
                            Log.d(TAG,"第"+i+"个数据删除删除成功");
                        } else {
                            Log.d(TAG,"第"+i+"个数据删除删除失败");
                        }
                    }
                } else {
                    Log.d(TAG,"删除失败"+e.getMessage());
                }
            }
        });

        return delete_success[0];
    }

    public void onImageDelete(boolean tf) {
            if(tf){
                this.mListener.onFragmentInteraction("show_tv_delete");
                Log.d(TAG,"show_tv_delete");
            }else {
                this.mListener.onFragmentInteraction("hide_tv_delete");
                Log.d(TAG,"hide_tv_delete");
            }
    }

    public void onSelectedItem(UserArtItem item){
        this.mListener.onFragmentInteraction(item);
    }

    public void onDeleteConfirm(int imgs){
        this.mListener.OnFabConfirm(imgs);
        RefreshData();
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    public void initData(){
        RefreshData();

    }
    public void initData2(){
        RefreshData();
        adapter.notifyDataSetChanged();
    }


    public void RefreshData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                BmobQuery<UserArt> bmobQuery = new BmobQuery<UserArt>();
                //假设传入了用户的信息，username为weixxx
                User user = new User();
                user = LoginUtil.getUserStatus();
                bmobQuery.addWhereEqualTo("username",user.getUsername());
                bmobQuery.findObjects(new FindListener<UserArt>(){
                    @Override
                    public void done(List<UserArt> result, BmobException e) {
                        if (e == null) {
                            users = new ArrayList<>();
                            users = result;
                            User user1 = new User();
                            if(null!=users&&users.size()>0) {
                                adapter = new DeleteAdapter(
                                        context,
                                        R.layout.item_delete_layout, users);
                                recyclerView.setAdapter(adapter);
                                swipe.setRefreshing(false);
                                Log.d(TAG,"查询成功,有数据"+users.size()+"条");
                            }else {
                                Log.d(TAG,"查询成功,无数据返回");
                                Toast.makeText(context,"查询成功,无数据返回",
                                        Toast.LENGTH_SHORT).show();

                                adapter = new DeleteAdapter(
                                        context,
                                        R.layout.item_layout, null);
                                recyclerView.setAdapter(adapter);
                                swipe.setRefreshing(false);
                            }

                        } else {
                            Log.d(TAG,e.toString());
                            Toast.makeText(context,"Error:"+e.toString(),
                                    Toast.LENGTH_SHORT).show();
                            adapter = new DeleteAdapter(
                                    context,
                                    R.layout.item_layout, null);
                            recyclerView.setAdapter(adapter);
                            swipe.setRefreshing(false);
                        }
                        adapter.notifyDataSetChanged();
                        changeSelect();
                    }
                });
            }
        }).start();
    }




}
